package cn.itcast.util;

import com.alibaba.fastjson.JSON;

import netscape.javascript.JSObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title: DBUtils
 * @ProjectName dop-java-demo
 * @Description:
 * @date 2018/10/24 17:35
 */
public class DBUtils {

    /**
     * 发送德邦开发平台接口请求
     *
     * @param url         接口地址
     * @param params      请求参数
     * @param companyCode 公司编码
     * @param appkey      APPKEY
     * @return
     * @throws UnsupportedEncodingException
     */
    public static final String postHttp(String url, String params, String companyCode, String appkey)
            throws UnsupportedEncodingException {
        // 构建参数
        String timestamp = String.valueOf(System.currentTimeMillis());
        String plaitText = params + appkey + timestamp;
        String digest = new String(Base64.encodeBase64(DigestUtils.md5Hex(plaitText).getBytes()));
        NameValuePair[] nameValuePairs = new NameValuePair[4];
        nameValuePairs[0] = new NameValuePair("companyCode", companyCode);
        nameValuePairs[1] = new NameValuePair("digest", digest);
        nameValuePairs[2] = new NameValuePair("timestamp", timestamp);
        nameValuePairs[3] = new NameValuePair("params", params);
        // 发送请求
        String responseMsg = "";
        // 构造HttpClient的实例
        HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        // 设置编码格式
        httpClient.getParams().setContentCharset("UTF-8");
        // 构造PostMethod的实例
        PostMethod postMethod = new PostMethod(url);
        // 设置Content-Type
        postMethod.setRequestHeader("Content-Type",
                "application/x-www-form-urlencoded;charset=utf-8");
        // 设置body
        postMethod.setRequestBody(nameValuePairs);
        postMethod.setRequestHeader("Connection", "close");
        try {
            // 执行postMethod,调用http接口
            httpClient.executeMethod(postMethod);
            // 读取内容
            responseMsg = postMethod.getResponseBodyAsString();
        } catch (HttpException e) {
            e.printStackTrace();
            throw new UnsupportedEncodingException(e.getClass().getName());
        } catch (IOException e) {
            e.printStackTrace();
            throw new UnsupportedEncodingException(e.getClass().getName());
        } finally {
            // 释放连接
            postMethod.releaseConnection();
            httpClient.getHttpConnectionManager().closeIdleConnections(0);
        }
        return responseMsg;

    }

    private static String getDigest(String plainText) {
        return Base64.encodeBase64String(DigestUtils.md5Hex(plainText).getBytes());
    }

    //
//    static String params = "{\"receiver\":{\"originalAddress\":\"\",\"phone\":\"\",\"provinceCode\":\"\",\"postCode\":\"\",\"cityCode\":\"\",\"companyName\":\"\",\"countyCode\":\"\",\"townCode\":\"\",\"city\":\"宿迁市\",\"address\":\"江苏省 宿迁市 宿城区. 幸福北路隆城丹郡20栋二单元2104室(000000).\",\"county\":\"宿城区,\",\"originalsStreet\":\"\",\"name\":\"周岩■\",\"province\":\"江苏省\",\"town\":\"\",\"mobile\":\"15050950333\"},\"orderType\":\"2\",\"companyCode\":\"EWBDOJJGFYXGS\",\"sender\":{\"originalAddress\":\"\",\"phone\":\"\",\"provinceCode\":\"\",\"postCode\":\"\",\"cityCode\":\"\",\"companyName\":\"四川帝王洁具有限公司\",\"countyCode\":\"\",\"townCode\":\"\",\"city\":\"成都市\",\"address\":\"成都市 简阳市 贾家镇工业园 四川帝王洁具有限公司\",\"county\":\"简阳市\",\"originalsStreet\":\"\",\"name\":\"黄怡\",\"province\":\"四川省\",\"town\":\"贾家镇\",\"mobile\":\"02887776500\"},\"needTraceInfo\":2,\"custOrderNo\":\"\",\"isOut\":\"N\",\"logisticID\":\"QIOC0608202105000043\",\"gmtCommit\":\"2021-05-08 11:44:48\",\"customerCode\":\"219401\",\"packageInfo\":{\"totalVolume\":0.3252,\"packageService\":\"纸\",\"deliveryType\":\"3\",\"totalWeight\":50,\"totalNumber\":1,\"cargoName\":\"货物名称\"},\"payType\":\"2\",\"insuranceValue\":2969,\"transportType\":\"RCP\"}";
//
    public static void main(String[] args) throws UnsupportedEncodingException {

        // long timestamp = 1620445488208L;
        String[] lists = new String[]{"DPK380019980303","DPK380019980304"};
        for (String list : lists) {
            TraceScri traceScri = new TraceScri();
            traceScri.setTracking_number(list);
            String params = JSON.toJSONString(traceScri);
//        System.out.println(Base64.class.getProtectionDomain().getCodeSource().getLocation());
//        String digest = getDigest(params + "4fba9166f5fc18040ff09accb005f3f1" + timestamp);
            String companyCode = "EWBBLGJ";
            String response = postHttp("http://dpapi.deppon.com/dop-interface-sync/dop-nonstandard-extension/standTraceSubscribe.action", params, companyCode, "deppontest");

            System.out.println(response);
        }
}

//        System.out.println(digest);
    }
//
//    public static String getFirstSpell(String chinese) {
//        StringBuffer pybf = new StringBuffer();
//        char[] arr = chinese.toCharArray();
//        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
//        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
//        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
//        for (int i = 0; i < arr.length; i++) {
//            if (arr[i] > 128) {
//                try {
//                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
//                    if (temp != null) {
//                        pybf.append(temp[0].charAt(0));
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            } else {
//                pybf.append(arr[i]);
//            }
//        }
//        return pybf.toString().replaceAll("\\W", "").trim();
//    }

//    public static final String sendRequest(String url, NameValuePair[] paramsList, String encoding, int timeout) {
//
//        // 校验URL SSRF
////        interceptSSRFUrl(url);
//
//        String tmpencoding = encoding;
//        int tmptimeout = timeout;
//
////        if (StringUtils.isEmpty(url)) {
////            return new ResultDO<String>()
////                    .setException(new NullPointerException("url empty"));
////        }
////        if (null == paramsList) {
////            return new ResultDO<String>()
////                    .setException(new NullPointerException("paramsList empty"));
////        }
////        if (StringUtils.isBlank(encoding)) {
//            tmpencoding = "UTF-8";
////        }
//        if (timeout <= 0) {
//            tmptimeout = 5000;
//        }
//
//        // 设置PostMethod
//        PostMethod postMethod = new PostMethod(url);
//        postMethod.getParams().setContentCharset(tmpencoding);
//        postMethod.getParams().setHttpElementCharset(tmpencoding);
//
//        // 设置body
//        postMethod.setRequestBody(paramsList);
//
//        // http client 参数设置 连接超时 读取数据超时
//        HttpClient httpClient = new HttpClient();
//        httpClient.getHttpConnectionManager().getParams()
//                .setConnectionTimeout(tmptimeout);
//        httpClient.getHttpConnectionManager().getParams().setSoTimeout(tmptimeout);
//
//        try {
//            httpClient.executeMethod(postMethod);
//            if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
//                return postMethod
//                        .getResponseBodyAsString();
//            }
//
//        } catch (Exception e) {
//
//        } finally {
//            postMethod.releaseConnection();
//        }
//        return "";
//    }

//    private static NameValuePair[] getRequestParams(String params, String companyCode,String appkey ) {
//
//        String timestamp = String.valueOf(System.currentTimeMillis());
//        String digest = getDigest(params + appkey + timestamp);
//
//        List<NameValuePair> nameValueList = new ArrayList<NameValuePair>();
//            nameValueList.add(new NameValuePair("params", params));
//            nameValueList.add(new NameValuePair("digest", digest));
//            nameValueList.add(new NameValuePair("timestamp", timestamp));
//            nameValueList.add(new NameValuePair("companyCode", companyCode));
//
//        return nameValueList.toArray(new NameValuePair[nameValueList.size()]);
//    }
//    public static void main(String[] args) {
//        String params = "{\"backSignBill\":\"0\",\"codPrice\":\"0\",\"codValue\":\"null\",\"comments\":\"\",\"deliveryPrice\":\"0\",\"fieldList\":[],\"gmtUpdated\":\"1620962058397\",\"insurancePrice\":\"12\",\"insuranceValue\":\"null\",\"logisticCompanyID\":\"DEPPON\",\"logisticID\":\"KORX169428290\",\"mailNo\":\"6710356856\",\"otherPrice\":\"null\",\"packageServicePrice\":\"0\",\"payType\":\"2\",\"receiver\":{\"address\":\"福永街道下十围银山物流中心A213\",\"city\":\"深圳市\",\"county\":\"宝安区\",\"mobile\":\"118123586520\",\"name\":\"张三\",\"province\":\"广东省\"},\"sender\":{\"address\":\"Test address\",\"city\":\"北京市\",\"county\":\"东城区\",\"mobile\":\"123\",\"name\":\"Test\",\"province\":\"北京市\"},\"smsNotifyPrice\":\"\",\"statusType\":\"GOT\",\"totalNumber\":\"0\",\"totalPrice\":\"689\",\"totalVolume\":\"null\",\"totalWeight\":\"null\",\"tracesList\":[],\"transportPrice\":\"616\",\"transportType\":\"PACKAGE\",\"waitNotifySend\":\"N\"}";
//        NameValuePair[] paramsList = getRequestParams(params, "EWBSZSXCMXXKJYXGS","efd77ad4f1abd788c8dd5d94683a8eaf");
//        System.out.println(sendRequest("http://3285w2r775.wicp.vip/tms/order/order/depponStatusPush", paramsList, "utf-8", 6000));
//    }

